package com.cms.recursoshumanos.json.me;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONException;
import org.json.JSONObject;
import org.xml.sax.SAXException;

import com.cms.recursoshumanos.constant.Constant;
import com.cms.recursoshumanos.xml.handler.XMLObjectHandler;

import android.util.Log;

public class JSONParser {

	static InputStream is = null;
	static JSONObject jObj = null;
	static String json = "";

	// constructor
	public JSONParser() {

	}
	
	public String getJSONFromUrl(String url, String peticion) 
	{

		// Making HTTP request
		try 
		{
			// defaultHttpClient
			
			HttpParams httpParams = new BasicHttpParams();
	        HttpConnectionParams.setConnectionTimeout(httpParams,70000);
	        HttpConnectionParams.setSoTimeout(httpParams, 70000);
	        HttpClient httpClient = new DefaultHttpClient(httpParams);
			HttpPost httpPost = new HttpPost(url);
			
			StringEntity se = new StringEntity(peticion); 
			
			httpPost.setEntity(se);
						
			HttpResponse httpResponse = httpClient.execute(httpPost);
			HttpEntity httpEntity = httpResponse.getEntity();
			//is = httpEntity.getContent();			
			json = null;
			if (httpEntity != null) 
			{
			 	is = httpEntity.getContent();
			 	json = convertStreamToString(is);
	            
			} 

			return json;
		
		} 
		catch (UnsupportedEncodingException e) 
		{
			e.printStackTrace();
			return null;
		} 
		catch (ClientProtocolException e) 
		{
			e.printStackTrace();
			return null;
		} 
		catch (IOException e) 
		{
			e.printStackTrace();
			return null;
		}
		catch (Exception e) 
		{	
			e.printStackTrace();
			return null;
		}
		
	}
	
	public String setPetitionToUrl(String url, String peticion) 
	{

		// Making HTTP request
		try 
		{
			// defaultHttpClient
			
			HttpParams httpParams = new BasicHttpParams();
	        HttpConnectionParams.setConnectionTimeout(httpParams,70000);
	        HttpConnectionParams.setSoTimeout(httpParams, 70000);
	        HttpClient httpClient = new DefaultHttpClient(httpParams);
			HttpPost httpPost = new HttpPost(url);
			
			StringEntity se = new StringEntity(peticion); 
			
			httpPost.setEntity(se);
						
			httpClient.execute(httpPost);
			

			return Constant.CODE_OK;
		
		} 
		catch (UnsupportedEncodingException e) 
		{
			e.printStackTrace();
			return null;
		} 
		catch (ClientProtocolException e) 
		{
			e.printStackTrace();
			return null;
		} 
		catch (IOException e) 
		{
			e.printStackTrace();
			return null;
		}
		catch (Exception e) 
		{	
			e.printStackTrace();
			return null;
		}
		
	}
	
	
	
	public String convertStreamToString(InputStream inputStream) throws IOException 
	{
		if (inputStream != null) 
		{
			StringBuilder sb = new StringBuilder();
			String line;
	
			try 
			{
				BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
				int cont = 0;
				while ((line = reader.readLine()) != null) 
				{
					if ((cont == 2 ) && !(line.substring(line.length()-2,line.length()).equals("e>")))
					{
						sb.append(line).append("e>\n");
					}
					else
					{
						sb.append(line).append("\n");
					}
					cont++;
				}
			}
			finally 
			{
				inputStream.close();
			}
			return parseXML(sb);
		}
		else{return "";}
	}
	
	public static String getXMLObjects(InputStream is) 
	{
        XMLObjectHandler xmlObjectHandler = new XMLObjectHandler();
        try 
        {
        	SAXParserFactory factory = SAXParserFactory.newInstance();	
  	      	SAXParser saxParser = factory.newSAXParser();
  	      	saxParser.parse(is, xmlObjectHandler);
        } 
        catch (SAXException e) 
        {
        	e.printStackTrace();
        } 
        catch (IOException e) 
        {
            e.printStackTrace();
        } 
        catch (ParserConfigurationException e) 
        {
        	e.printStackTrace();
		}
        return xmlObjectHandler.getXMLResult();
    }
	public String parseXML(StringBuilder sb)
	{
		String xml = sb.toString();
		String arreglo_ayuda = xml.substring(2,xml.length()-1);
        ByteArrayInputStream bais = new ByteArrayInputStream(arreglo_ayuda.getBytes());       
        return getXMLObjects(bais);
	}
	
	public JSONObject getJSONFromUrl1(String url) {

		// Making HTTP request
		try {
			// defaultHttpClient
			DefaultHttpClient httpClient = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost(url);

			HttpResponse httpResponse = httpClient.execute(httpPost);
			HttpEntity httpEntity = httpResponse.getEntity();
			is = httpEntity.getContent();			

		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					is, "iso-8859-1"), 8);
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
			is.close();
			json = sb.toString();
		} catch (Exception e) {
			Log.e("Buffer Error", "Error converting result " + e.toString());
		}

		// try parse the string to a JSON object
		try {
			jObj = new JSONObject(json);
		} catch (JSONException e) {
			Log.e("JSON Parser", "Error parsing data " + e.toString());
		}

		// return JSON String
		return jObj;

	}
}
